package com.qf.controller;

import com.qf.feign.OrderServiceFeign;
import com.qf.pojo.Order;
import com.qf.pojo.R;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.print.attribute.standard.PrinterURI;
import java.util.List;

//@RestController
//@RequestMapping("/user")
//@RefreshScope //在感知到配置变化后，将当前注解修饰的对象重建
public class UserController {

    @Value("${desc}")
    private String desc;

    @Autowired
    private RestTemplate restTemplate;

    //注入一个服务发现对象
    @Autowired
    private DiscoveryClient discoveryClient;

    //注入一个负载均衡器对象
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private OrderServiceFeign orderServiceFeign;

    @GetMapping("/{id}")
    public R findOrders(@PathVariable("id") Integer id) throws InterruptedException {
        //发现服务
//        List<ServiceInstance> instances = discoveryClient.getInstances("qf-order");
//        ServiceInstance serviceInstance = instances.get(0);

       /* //利用负载均衡器实现负载均衡
        ServiceInstance serviceInstance = loadBalancerClient.choose("qf-order");

        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();

        //发起远程访问
        R r = restTemplate.getForObject("http://"+host+":"+port+"/order/" + id, R.class);*/

        //将负载均衡器和RestTemplate实现整合后的调用方式
//        R r = restTemplate.getForObject("http://qf-order/order/" + id, R.class);

        //利用Feign实现远程调用 (问题：通过Feign远程调用时，头信息会丢失)
        //Feign实现远程调用请求头丢失的原因，因为Feign内部会自建一个新的请求对象，利用这个请求对象发起远程访问
        R r = orderServiceFeign.findByUid(id);

        System.out.println("========================" + desc);
        return r;
    }
}
